import React from 'react';
import routes from '../routes';
import PropTypes from 'prop-types';
import {Link} from 'react-router-dom';
import {
    PAGE,
    TABLE,
    DATETIME_FORMAT,
    PAGINATION_OPTIONS,
    COMMON_TABLE_QUERY_FAIL_TEXT,
    COMMON_TABLE_EMPTY_TEXT,
    FIXED_COLUMN_WIDTH
} from '../../constants';
import {PERMISSION} from '../constants';
import ImportPanel from '../ImportPanel';
import {Table, Card, message} from 'antd';
import {injectIntl, formatMessage} from '../intl';
import {conventSorter, hasPermissions} from '../utils';
import DropdownMenu from 'Shared/components/DropdownMenu';
import {technologyActivityStatus, isTorF} from '../../Enum';
import WrappedPopconfirm from '../../common/WrappedPopconfirm';
import {formatDateTime, conventEnumValueToString} from '../../utils';
export class TablePanel extends React.PureComponent {
    state = {
        vinId: '',
        loading: false,
        showImport: false
    };
    handleAbandon = id => {
        this.setState({
            loading: true
        });
        this.props.onClickAbandon(id).then(() => {
            this.setState({
                loading: false
            });
        });
    };
    handleSubmit = id => {
        this.setState({
            loading: true
        });
        this.props.onClickSubmit(id).then(() => {
            this.setState({
                loading: false
            });
        });
    };
    handlePublish = id => {
        this.setState({
            loading: true
        });
        this.props.onClickPublish(id).then(() => {
            this.setState({
                loading: false
            });
        });
    };
    handleClose = id => {
        this.setState({
            loading: true
        });
        this.props.onClickClose(id).then(() => {
            this.setState({
                loading: false
            });
        });
    };
    importChange = data => {
        if(data) {
            this.setState({showImport: false});
            message.success(formatMessage({
                id: 'queryPanel.msg.importVIN',
                defaultMessage: '导入VIN成功'
            }));
            this.props.querySearch();
        }
    }
    onChangeSort = (pagination, filters, sorter) => {
        if(pagination.current - 1 === this.props.pageIndex && pagination.pageSize === this.props.pageSize)
            this.props.onChangeSort({...conventSorter(sorter),
                pageIndex: PAGE.index});
    };
    onImport = id => this.setState({
        vinId: id,
        showImport: true

    });
    onCloseImport = () => this.setState({showImport: false});
    render() {
        const {pageIndex, pageSize, total, permissions, isDealerUser} = this.props;
        const columns = [{
            title: formatMessage({
                id: 'tablePanel.column.code',
                defaultMessage: '编号'
            }),
            dataIndex: 'code',
            sorter: true,
            render: (text, record) => (
                <Link key="detail" to={routes.detail.format(record.id)}>
                    {text}
                </Link>
            )
        }, {
            title: formatMessage({
                id: 'tablePanel.column.serviceName',
                defaultMessage: '技术升级主题'
            }),
            dataIndex: 'serviceName',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.dealerCode',
                defaultMessage: '总代'
            }),
            dataIndex: 'dealerCode',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.country',
                defaultMessage: '国家'
            }),
            dataIndex: 'country',
        }, {
            title: formatMessage({
                id: 'tablePanel.column.status',
                defaultMessage: '状态'
            }),
            dataIndex: 'status',
            sorter: true,
            render: text => conventEnumValueToString(technologyActivityStatus, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.startTime',
                defaultMessage: '开始时间'
            }),
            dataIndex: 'startTime',
            sorter: true,
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.endTime',
                defaultMessage: '技术升级截止时间'
            }),
            dataIndex: 'endTime',
            sorter: true,
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.content',
                defaultMessage: '主要内容'
            }),
            dataIndex: 'content',
            sorter: true,
        }, {
            title: formatMessage({
                id: 'tablePanel.column.isDealerApply',
                defaultMessage: '是否总代申请'
            }),
            dataIndex: 'isDealerApply',
            sorter: true,
            render: text => conventEnumValueToString(isTorF, text)
        }, {
            title: formatMessage({
                id: 'tablePanel.column.action',
                defaultMessage: '操作'
            }),
            dataIndex: 'action',
            width: FIXED_COLUMN_WIDTH,
            fixed: 'right',
            render: (t, r) => {
                const menus = [
                    {
                        id: PERMISSION.update,
                        children: (
                            <Link key="update" to={routes.update.format(r.id)}>
                                {formatMessage({
                                    id: 'tablePanel.operation.update',
                                    defaultMessage: '编辑'
                                })}
                            </Link>
                        ),
                        hidden: !(hasPermissions(permissions, PERMISSION.update) && hasPermissions(r.options, PERMISSION.update))
                    }, {
                        id: PERMISSION.addVin,
                        children: (
                            <div key="addVin" onClick={() => this.onImport(r.id)}>
                                {formatMessage({
                                    id: 'tablePanel.operation.addVin',
                                    defaultMessage: '添加VIN'
                                })}
                            </div>
                        ),
                        hidden: !(hasPermissions(permissions, PERMISSION.addVin) && hasPermissions(r.options, PERMISSION.addVin))
                    }, {
                        id: PERMISSION.abandon,
                        children: ref =>
                            <WrappedPopconfirm
                                id={r.id}
                                key="abandon"
                                title={formatMessage({
                                    id: 'tablePanel.popconfirm.message',
                                    defaultMessage: '是否继续?'
                                })}
                                onVisibleChange={ref.setMenuVisible}
                                onConfirm={this.handleAbandon}>
                                <a key="abandon">
                                    {formatMessage({
                                        id: 'tablePanel.operation.abandon',
                                        defaultMessage: '作废'
                                    })}
                                </a>
                            </WrappedPopconfirm>,
                        hidden: !(hasPermissions(permissions, PERMISSION.abandon) && hasPermissions(r.options, PERMISSION.abandon))
                    }];
                // eslint-disable-next-line no-negated-condition
                if(!isDealerUser)
                    menus.push({
                        id: PERMISSION.release,
                        children: ref =>
                            <WrappedPopconfirm
                                id={r.id}
                                key="release"
                                title={formatMessage({
                                    id: 'tablePanel.popconfirm.message',
                                    defaultMessage: '是否继续?'
                                })}
                                onVisibleChange={ref.setMenuVisible}
                                onConfirm={this.handlePublish}>
                                <a key="release">
                                    {formatMessage({
                                        id: 'tablePanel.operation.release',
                                        defaultMessage: '发布'
                                    })}
                                </a>
                            </WrappedPopconfirm>,
                        hidden: !(hasPermissions(permissions, PERMISSION.release) && hasPermissions(r.options, PERMISSION.release))
                    }, {
                        id: PERMISSION.close,
                        children: ref =>
                            <WrappedPopconfirm
                                id={r.id}
                                key="close"
                                title={formatMessage({
                                    id: 'tablePanel.popconfirm.message',
                                    defaultMessage: '是否继续?'
                                })}
                                onVisibleChange={ref.setMenuVisible}
                                onConfirm={this.handleClose}>
                                <a key="close">
                                    {formatMessage({
                                        id: 'tablePanel.operation.close',
                                        defaultMessage: '关闭'
                                    })}
                                </a>
                            </WrappedPopconfirm>,
                        hidden: !(hasPermissions(permissions, PERMISSION.close) && hasPermissions(r.options, PERMISSION.close))
                    }, {
                        id: PERMISSION.approve,
                        children: (
                            <Link key="approve" to={routes.approve.format(r.id)}>
                                {formatMessage({
                                    id: 'tablePanel.operation.approve',
                                    defaultMessage: '审核'
                                })}
                            </Link>
                        ),
                        hidden: !(hasPermissions(permissions, PERMISSION.approve) && hasPermissions(r.options, PERMISSION.approve))
                    });
                else
                    menus.push({
                        id: PERMISSION.submit,
                        children: ref =>
                            <WrappedPopconfirm
                                id={r.id}
                                key="submit"
                                title={formatMessage({
                                    id: 'tablePanel.popconfirm.message',
                                    defaultMessage: '是否继续?'
                                })}
                                onVisibleChange={ref.setMenuVisible}
                                onConfirm={this.handleSubmit}>
                                <a key="submit">
                                    {formatMessage({
                                        id: 'tablePanel.operation.submit',
                                        defaultMessage: '提交'
                                    })}
                                </a>
                            </WrappedPopconfirm>,
                        hidden: !(hasPermissions(permissions, PERMISSION.submit) && hasPermissions(r.options, PERMISSION.submit))
                    });
                
                return <DropdownMenu key={r.id} menus={menus} primaryLength={1} id={r.id} />;
            }
        }];
        const pagination = {
            total,
            pageSize,
            current: pageIndex + 1,
            onShowSizeChange: this.props.onPageSizeChange,
            onChange: this.props.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: this.props.hasError ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        return (
            <Card>
                <Table
                    className="white-space-nowrap"
                    columns={columns}
                    dataSource={this.props.data}
                    rowKey="id"
                    pagination={pagination}
                    loading={this.props.loading || this.state.loading}
                    onChange={this.onChangeSort}
                    locale={locale}
                    {...TABLE}/>
                {
                    this.state.showImport &&
                        <ImportPanel
                            vinId={this.state.vinId}
                            onCancel={this.onCloseImport}
                            onImportChange={this.importChange} />
                }
            </Card>
        );
    }
}

TablePanel.propTypes = {
    data: PropTypes.array.isRequired,
    hasError: PropTypes.string.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    querySearch: PropTypes.func.isRequired,
    total: PropTypes.number.isRequired,
    onChangeSort: PropTypes.func.isRequired,
    onClickAbandon: PropTypes.func.isRequired,
    onClickClose: PropTypes.func.isRequired,
    onClickPublish: PropTypes.func.isRequired,
    onClickSubmit: PropTypes.func.isRequired,
    onPageIndexChange: PropTypes.func.isRequired,
    onPageSizeChange: PropTypes.func.isRequired,
    isDealerUser: PropTypes.bool,
    pageIndex: PropTypes.number,
    pageSize: PropTypes.number,
};
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {tableSearch, onClickAbandon, onClickSubmit, onClickPublish, onClickClose, querySearch} from '../actions';
const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    data: getData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    hasError: state.getIn(['page', 'domainData', 'list', 'hasError']),
    total: state.getIn(['page', 'domainData', 'list', 'total']),
    pageIndex: state.getIn(['page', 'appState', 'queryBySort', 'pageIndex']),
    pageSize: state.getIn(['page', 'appState', 'queryBySort', 'pageSize']),
    isDealerUser: state.getIn((['page', 'domainData', 'init', 'isDealerUser'])),
    permissions: getPermissions(state)
});

const mapDispatchToProps = dispatch => ({
    querySearch: () => dispatch(querySearch()),
    onPageSizeChange: (pageIndex, pageSize) =>
        dispatch(
            tableSearch({
                pageIndex: PAGE.index,
                pageSize
            })
        ),
    onPageIndexChange: pageIndex =>
        dispatch(
            tableSearch({
                pageIndex: pageIndex - 1
            })
        ),
    onChangeSort: option => dispatch(tableSearch(option)),
    onClickAbandon: id =>
        dispatch(onClickAbandon(id)).then(success => {
            if(success) dispatch(querySearch());
            return success;
        }),
    onClickSubmit: id =>
        dispatch(onClickSubmit(id)).then(success => {
            if(success) dispatch(querySearch());
            return success;
        }),
    onClickPublish: id =>
        dispatch(onClickPublish(id)).then(success => {
            if(success) dispatch(querySearch());
            return success;
        }),
    onClickClose: id =>
        dispatch(onClickClose(id)).then(success => {
            if(success) dispatch(querySearch());
            return success;
        }),
});
import {connect} from 'react-redux';
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanel));
